import React, { useState, useContext } from 'react'
import { Button } from 'antd'
import { ADD_TODO } from './reducer'
import Store from './context'

const TodoHeaderHooks = () => {
    const { state, dispatch } = useContext(Store)
    console.log('Header组件=====>>>')
    console.log(state)
    const [todo, setTodo] = useState('')
    function handleTodoChange(e) {
        setTodo(e.target.value)
    }
    const handleTodoAdd = () => {
        dispatch({
            type: ADD_TODO,
            payload: {
                id: +new Date(),
                title: todo,
                isComplete: false
            }
        })
        setTodo('')
    }
    const handleSubmitForm = event => {
        if (event.keyCode === 13) handleTodoAdd()
    }
    const getUnfinishedCount = () => state.todos.filter(i => !i.isComplete).length

    return (
        <div>
            <div>
                您有
                {getUnfinishedCount()}
                件事未完成
          </div>
            <div>
            <label htmlFor="todo">待办项：</label>
            <input
                    type="text"
                    value={todo}
                  onKeyUp={handleSubmitForm}
                  onChange={handleTodoChange} />
                <Button type="default" onClick={handleTodoAdd}>
                    添加
              </Button>
          </div>
      </div>
    )
}

export default TodoHeaderHooks
